#include "Usart.h"

uint8_t Serial_RxData;
uint8_t Serial_RxFlag;
uint8_t Serial_usart1_RxData;
uint8_t Serial_usart1_RxFlag;
uint8_t Serial_usart2_RxData;
uint8_t Serial_usart2_RxFlag;
uint8_t Serial_usart3_RxData;
uint8_t Serial_usart3_RxFlag;
void Usart_Init(void)
{
	// 打开GPIO和USART的时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	// 串口1配置（保持不变）
	GPIO_InitTypeDef GPIOA9_InitStructure;
	GPIOA9_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIOA9_InitStructure.GPIO_Pin = GPIO_Pin_9;
	GPIOA9_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIOA9_InitStructure);
	
	GPIO_InitTypeDef GPIOA10_InitStructure;
	GPIOA10_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIOA10_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIOA10_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIOA10_InitStructure);
	
	
	// 配置GPIOA_0口（LED灯，保持不变）
	GPIO_InitTypeDef GPIOA0_InitStructure;
	GPIOA0_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIOA0_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIOA0_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIOA0_InitStructure);
	
	// 串口1通信参数配置（保持不变）
	USART_InitTypeDef USART1_InitSturcture;
	USART1_InitSturcture.USART_BaudRate = 9600;
	USART1_InitSturcture.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART1_InitSturcture.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART1_InitSturcture.USART_Parity = USART_Parity_No;
	USART1_InitSturcture.USART_StopBits = USART_StopBits_1;
	USART1_InitSturcture.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART1, &USART1_InitSturcture);
	
	// 串口1中断配置（保持不变）
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef NVIC_USART_InitStructyre;
	NVIC_USART_InitStructyre.NVIC_IRQChannel = USART1_IRQn;
	NVIC_USART_InitStructyre.NVIC_IRQChannelCmd = ENABLE;
	NVIC_USART_InitStructyre.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_USART_InitStructyre.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_USART_InitStructyre);
	USART_Cmd(USART1, ENABLE);
	
	// 串口2配置（替代原串口3）
	// 1. 开启串口2时钟（APB1总线）和对应GPIOA时钟（串口2使用PA2/PA3引脚）
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);  // 串口2位于APB1总线
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);   // 串口2使用PA引脚（已在串口1中使能，此处可省略）
	
	// 2. 配置串口2引脚：PA2(TX)为复用推挽输出，PA3(RX)为上拉输入
	GPIO_InitTypeDef GPIO_USART2_Init;
	// TX引脚 (PA2)
	GPIO_USART2_Init.GPIO_Pin = GPIO_Pin_2;
	GPIO_USART2_Init.GPIO_Mode = GPIO_Mode_AF_PP;      // 复用推挽输出
	GPIO_USART2_Init.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_USART2_Init);
	// RX引脚 (PA3)
	GPIO_USART2_Init.GPIO_Pin = GPIO_Pin_3;
	GPIO_USART2_Init.GPIO_Mode = GPIO_Mode_IPU;        // 上拉输入
	GPIO_Init(GPIOA, &GPIO_USART2_Init);
	
	// 3. 配置USART2参数（与原串口3相同）
	USART_InitTypeDef USART2_InitSturcture;
	USART2_InitSturcture.USART_BaudRate = 9600;
	USART2_InitSturcture.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART2_InitSturcture.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART2_InitSturcture.USART_Parity = USART_Parity_No;
	USART2_InitSturcture.USART_StopBits = USART_StopBits_1;
	USART2_InitSturcture.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART2, &USART2_InitSturcture);
	
	// 4. 开启USART2接收中断
	USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
	
	// 5. 配置USART2中断优先级
	NVIC_InitTypeDef NVIC_USART2_InitStructyre;
	NVIC_USART2_InitStructyre.NVIC_IRQChannel = USART2_IRQn;  // 串口2中断通道
	NVIC_USART2_InitStructyre.NVIC_IRQChannelCmd = ENABLE;
	NVIC_USART2_InitStructyre.NVIC_IRQChannelPreemptionPriority = 2;  // 与原串口3相同优先级
	NVIC_USART2_InitStructyre.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_USART2_InitStructyre);
	
	// 6. 使能串口2
	USART_Cmd(USART2, ENABLE);
}
//===================================================串口1函数===================================================
void USART1_SendDate(uint8_t Byte)
{
	USART_SendData(USART1,Byte);
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE) == RESET);
}

void USART1_SendArray(uint8_t *Array,uint8_t size)
{
	uint8_t i = 0;
	while(i < size)
	{
		USART1_SendDate(Array[i]);
		i++;
	}
}
void USART1_SendString(char *String)
{
	uint8_t i = 0;
	while(String[i] != '\0')
	{
		USART1_SendDate(String[i]);
		i++;
	}
}
void USART1_Printf(char *format,...)
{
	char String[100];
	va_list arg;
	va_start(arg,format);
	vsprintf(String,format,arg);
	va_end(arg);
	USART1_SendString(String);
}
void LED1_ON(void)
{
	GPIO_ResetBits(GPIOA, GPIO_Pin_0);
}

void LED1_OFF(void)
{
	GPIO_SetBits(GPIOA, GPIO_Pin_0);
}
uint8_t Date_usart1_count = 0;
uint8_t Date_array[5];
uint8_t Date_usart1_array[5];
uint8_t Date_usart1_flag = 0;
uint8_t Date_usart1_flag_x = 0;
uint8_t Date_usart1_flag_d = 0;
uint16_t Obj_x = 0;
uint16_t Obj_d = 0;
uint16_t Get_x(uint8_t date) {
    // 状态切换指令
    if(date == 'x') {
        Date_usart1_flag_x = 1;
        Date_usart1_flag_d = 0;
        Date_usart1_count = 0;
        return 0;
    }
    if(date == 'd') {
        Date_usart1_flag_d = 1;
        Date_usart1_flag_x = 0;
        Date_usart1_count = 0;
        return 0;
    }
    
    // 结束指令
    if(date == 'e') {
        if(Date_usart1_flag_x || Date_usart1_flag_d) {
            uint16_t result = Date_usart1_array[0]*100 + 
                             Date_usart1_array[1]*10 + 
                             Date_usart1_array[2];
            
            if(Date_usart1_flag_x) Obj_x = result;
            if(Date_usart1_flag_d) Obj_d = result;
            
            // 仅重置当前状态
            Date_usart1_flag_x = 0;
            Date_usart1_flag_d = 0;
        }
        return 0;
    }
    
    // 数字处理（仅接受0-9）
    if((Date_usart1_flag_x || Date_usart1_flag_d) && (date >= '0' && date <= '9')) {
        if(Date_usart1_count < 3) {
            Date_usart1_array[Date_usart1_count] = date - '0'; // ASCII转数字
            Date_usart1_count++;
        }
    }
    return 1;
}


uint16_t Get_Date(uint8_t date) 
{
    // 状态切换指令
    if(date == 'x') {
        Date_usart1_flag_x = 1;
        Date_usart1_flag_d = 0;
        Date_usart1_count = 0;
        return 0;
    }
    if(date == 'd') {
        Date_usart1_flag_d = 1;
        Date_usart1_flag_x = 0;
        Date_usart1_count = 0;
        return 0;
    }
    
    // 结束指令
    if(date == 'e') 
	{
		if(Date_usart1_flag_x) {USART2_process('x');}
		if(Date_usart1_flag_d) {USART2_process('d');}
		
		// 仅重置当前状态
		Date_usart1_flag_x = 0;
		Date_usart1_flag_d = 0;
        return 0;
    }
    
    // 数字处理（仅接受0-9）
    if((Date_usart1_flag_x || Date_usart1_flag_d) && (date >= '0' && date <= '9')) 
	{
        if(Date_usart1_count < 5) 
		{
            Date_usart1_array[Date_usart1_count] = date; // ASCII转数字
            Date_usart1_count++;
        }
    }
    return 1;
}
//===================================================串口2函数===================================================
// USART3专用函数
void USART2_SendDate(uint8_t Byte)
{
	USART_SendData(USART2,Byte);
	while(USART_GetFlagStatus(USART2,USART_FLAG_TXE) == RESET);
}

void USART2_SendArray(uint8_t *Array,uint8_t size)
{
	uint8_t i = 0;
	while(i < size)
	{
		USART2_SendDate(Array[i]);
		i++;
	}
}
void USART2_SendString(char *String)
{
	uint8_t i = 0;
	while(String[i] != '\0')
	{
		USART2_SendDate(String[i]);
		i++;
	}
}
void USART2_Printf(char *format,...)
{
	char String[100];
	va_list arg;
	va_start(arg,format);
	vsprintf(String,format,arg);
	va_end(arg);
	USART2_SendString(String);
}
//串口2
//t2距离t4边长t6面积
void USART2_SendEnd(void)
{
	USART2_SendString("\"\xFF\xFF\xFF");
}
void USART2_SendSTx(uint8_t t_num)
{
	switch(t_num)
	{
		case 2:
			USART2_SendString("t2.txt=\"");break;
		case 4:
			USART2_SendString("t4.txt=\"");break;
		case 6:
			USART2_SendString("t6.txt=\"");break;
	}
}
//USART2_SendString("t6.txt=\"600\"\xFF\xFF\xFF");
void USART2_SendX(uint8_t date[5],uint8_t date_num)
{
	uint8_t i = date_num;
	while(i)
	{
		USART2_SendDate(date[date_num-i]);
		i--;
	}
}
void USART2_process(char date)
{
	uint8_t tx = 0;
		switch(date)
	{
		case 'x':
			tx = 4;break;
		case 'd':
			tx = 2;break;
	}
	USART2_SendSTx(tx);
//	Date_usart1_array[0] = '1';
//	Date_usart1_array[1] = '2';
//	Date_usart1_array[2] = '1';
//	Date_usart1_array[3] = '1';
//	Date_usart1_count = 4;
	USART2_SendX(Date_usart1_array,Date_usart1_count);
	USART2_SendEnd();
}



//===================================================串口1中断函数===================================================
//到启动文件_md.s中查看中断向量表，确认中断程序名
void USART1_IRQHandler(void)
{
	if (USART_GetITStatus(USART1, USART_IT_RXNE) == SET)
	{
		Serial_RxData = USART_ReceiveData(USART1);
		Serial_RxFlag = 1;
		USART_ClearITPendingBit(USART1, USART_IT_RXNE);
	}
	//数据回传
	//USART2_SendDate(Serial_RxData);
	Get_Date(Serial_RxData);
	//Get_x(Serial_RxData);
	//注意这里的1并不是字符1，字符1还要看ascill码表
	switch(Serial_RxData)
	{
		//事件1点灯：
		case 1:
			LED1_ON();
		break;
		//事件2灭灯：
		case 2:
			LED1_OFF();
		break;
	}
}
//===================================================串口2中断函数===================================================
void USART2_IRQHandler(void)
{
	if (USART_GetITStatus(USART2, USART_IT_RXNE) == SET)
	{
		Serial_usart2_RxData = USART_ReceiveData(USART2);
		Serial_usart2_RxFlag = 1;
		USART_ClearITPendingBit(USART2, USART_IT_RXNE);
	}
	LED1_OFF();
	//数据回传
	//USART2_SendDate(Serial_usart2_RxData);
}
